package cae.gui.msg;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;

import cae.gui.util.CaeAlert;
import cae.logic.CaeMessageSender;
import cae.logic.destination.CaeDestination;

public class CaeSendDialog extends JDialog implements ActionListener 
{
	private static final long serialVersionUID = 1L;
	private JPanel panel = null;
	
	private JTextArea textArea;
	private CaeDestination dest;
	private static Logger logger = Logger.getLogger(CaeSendDialog.class);
	
	public CaeSendDialog(JFrame frame, CaeDestination dest)
	{
		super(frame, "Enviar Mensaje a "+dest.getAlias(), true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.dest = dest;
		
		panel = new JPanel(new BorderLayout());
		getContentPane().add(panel);

		textArea = new JTextArea(10, 40);
		textArea.setLineWrap(true);
		panel.add(new JScrollPane(textArea), BorderLayout.CENTER);
		
		JButton sendB = new JButton("Enviar");
		sendB.addActionListener(this);
		panel.add(sendB, BorderLayout.SOUTH);
		
		pack();
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(screenSize.width / 4, screenSize.height /4);
        
		setResizable(false);
		setAlwaysOnTop(true);
		setVisible(true);
		
		// TODO FOCO
		//FocusManager.getCurrentManager().
		
	}

	public void actionPerformed(ActionEvent e)
	{
		new Thread(new Runnable()
		{
			public void run() 
			{
				try {
					CaeMessageSender.sendMessage(textArea.getText(), dest);
				} catch (IOException e) {
					CaeAlert.error("No se ha podido enviar el mensaje a " + dest.getAlias() +"\n"+
							e.getMessage(), null);
					logger.error("No se ha podido enviar el mensaje a " + dest.getAlias(), e);
				}
			}
		}).start();
		setVisible(false);
	}
}

